/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import se.chalmers.ait.dat215.project.Product;

/**
 *
 * @author Andreas
 */
public class ProductPresenter {

    private ProductView productView;
    private Product product;
    private DecimalFormat nf = new DecimalFormat();

    public ProductPresenter(ProductView view) {
        productView = view;
        nf.setMinimumFractionDigits(2);
    }

    public void setProduct(Product p) {
        product = p;

        productView.getNameLabel().setText(product.getName());
        JLabel imageLabel = productView.getImage();
        imageLabel.setIcon(DataHandler.getInstance().getImageIcon(product, 133, 100));
        productView.getPriceLabel().setText(nf.format(product.getPrice())+" "+product.getUnit());

        if (DataHandler.getInstance().isFavorite(product)) {
            productView.getStarButton().setImageBackground("star-full.png");
        }
        else {
            productView.getStarButton().setImage("star-empty.png");
        }
    }

    public void addToTrolley() {
        if (product != null) {
            DataHandler.getInstance().addToShoppingCart(product);
        }
        else {
            Logger.getLogger(IMatView.class.getName()).log(Level.SEVERE, "No product to add.");
        }
        
    }

    public void favoriteClicked() {
        if (DataHandler.getInstance().isFavorite(product)) {
            removeFavorite();
            productView.getStarButton().setImage("star-empty.png");
        }
        else {
            addFavorite();
            productView.getStarButton().setImage("star-full.png");
        }
    }

    private void addFavorite() {
        if (product != null) {
            DataHandler.getInstance().addFavorite(product);
        }
    }

    private void removeFavorite() {
        if (product != null) {
            DataHandler.getInstance().removeFavorite(product);
        }
    }
}
